package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.vo.OrderReportVO;
import com.sky.vo.SalesTop10ReportVO;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.UserReportVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    /**
     * 营业额统计
     * @param startDate
     * @param endDate
     * @return
     */
    @Override
    public TurnoverReportVO turnOverStatistics(LocalDate startDate, LocalDate endDate) {
        //当前集合存储从startDate到endDate的所有日期
        List<LocalDate> dateList = new ArrayList();
        dateList.add(startDate);
        while (!startDate.equals(endDate)) {
            //日期加1，startDate往后一天，直到等于endDate
            startDate = startDate.plusDays(1);
            dateList.add(startDate);
        }
        //存放每天的营业额
        List<Double> turnoverList=new ArrayList<>();
        for(LocalDate date : dateList){
            //查询data日期对应的营业额,营业额状态为：“已完成”的订单
            LocalDateTime startTime=LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime=LocalDateTime.of(date, LocalTime.MAX);

            Map map=new HashMap();
            map.put("startTime",startTime);
            map.put("endTime",endTime);
            map.put("status", Orders.COMPLETED);

            Double turnover=orderMapper.sumByMap(map);
            //如果营业额为null，设置为0
            turnover = turnover==null?0:turnover;
            turnoverList.add(turnover);

        }
        return TurnoverReportVO.builder()
                //日期，以逗号分隔
                .dateList(StringUtils.join(dateList, ","))
                //营业额，以逗号分隔
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //当前集合存储从begin到end的所有日期
        List<LocalDate> dateList = new ArrayList();
        dateList.add(begin);
        while (begin.isBefore(end)){
            //日期加1，begin往后一天，直到等于end
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //存放每天新增的用户数量 select count(id) from user where create_time > #{startTime} and creat_time < #{endTime}
        List<Integer> newUserList=new ArrayList<>();
        //存放每天全部的用户数量 select count(id) from user where create_time < #{endTime}
        List<Integer> totalUserList=new ArrayList<>();

        for(LocalDate date : dateList){
            //查询data日期对应的新增用户数量
            LocalDateTime beginTime=LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime=LocalDateTime.of(date, LocalTime.MAX);

            Map map=new HashMap();

            map.put("endTime",endTime);

            Integer totalUser=userMapper.countByMap(map);
            //如果全部用户数量为null，设置为0
            totalUser = totalUser==null?0:totalUser;
            totalUserList.add(totalUser);

            //查询data日期对应的全部用户数量
            map.put("beginTime",beginTime);

            Integer newUser=userMapper.countByMap(map);
            //如果新增用户数量为null，设置为0
            newUser = newUser==null?0:newUser;
            newUserList.add(newUser);
        }
        return UserReportVO.builder()
            .dateList(StringUtils.join(dateList, ","))//日期，以逗号分隔
            .newUserList(StringUtils.join(newUserList, ","))//新增用户数量，以逗号分隔
            .totalUserList(StringUtils.join(totalUserList, ","))//全部用户数量，以逗号分隔
            .build();
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {
        //当前集合存储从begin到end的所有日期
        List<LocalDate> dateList = new ArrayList();
        dateList.add(begin);
        while (begin.isBefore(end)) {
            //日期加1，begin往后一天，直到等于end
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //存放每天的订单数量
        List<Integer> orderCountList = new ArrayList<>();
        //存放每天的有效订单数量
        List<Integer> validOrderCountList = new ArrayList<>();
        //查询每天的有效订单数量与完成的订单数量

        for (LocalDate date : dateList) {
            //精确时间值
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //查询每天的订单数量
            Integer orderCount = getOrderCount(beginTime, endTime, null);
            //查询每天的有效订单数量
            Integer ValidOrderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);

            orderCountList.add(orderCount);
            validOrderCountList.add(ValidOrderCount);
        }
            //计算时间内的订单总数量
            Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
            //计算时间内的有效的订单总数量
            Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
            //计算订单完成率
            Double orderCompletionRate = 0.0;
            if (totalOrderCount != 0) {
                orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount.doubleValue();
            }


        return OrderReportVO.builder()
                //日期，以逗号分隔
                .dateList(StringUtils.join(dateList, ","))
                //订单数量，以逗号分隔
                .orderCountList(StringUtils.join(orderCountList, ","))
                //有效订单数量，以逗号分隔
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                //订单总数量
                .totalOrderCount(totalOrderCount)
                //有效订单总数量
                .validOrderCount(validOrderCount)
                //订单完成率
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 根据条件订单统计数量
     * @param begin
     * @param end
     * @param status
     * @return
     */
    private Integer getOrderCount(LocalDateTime begin, LocalDateTime end, Integer status){
        Map map=new HashMap();
        map.put("beginTime",begin);
        map.put("endTime",end);
        map.put("status",status);

        return orderMapper.countByMap(map);
    }
    /**
     * 销售额top10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO SalesTop10Statistics(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        Map map=new HashMap();
        map.put("beginTime",begin);
        map.put("endTime",end);
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getGoodsSales(map);

        List<String>names=goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer>numbers=goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(names, ","))
                .numberList(StringUtils.join(numbers, ","))
                .build();
    }
}
